﻿using MvcShoppingMall.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcShoppingMall.Controllers
{
    /// <summary>
    /// 用户主页面
    /// </summary>
    public class UserController : BaseController
    {
        //
        // GET: /User/

        #region 个人中心首页、我的订单
        public ActionResult UserCenterIndex()
        {

            return View();
        }
        #endregion

        #region 订单物流详情
        public ActionResult Details()
        {

            return View();
        }
        #endregion

        #region 我的关注，店铺、商品的收藏
        public ActionResult MyAttention()
        {

            return View();
        }
        #endregion

        #region 个人信息
        public ActionResult UserInfo(int id = 1)
        {
            //根据用户Id返回集合中第一个实体对象
            wst_users user = (from a in dbContext.wst_users where a.userId == id select a).FirstOrDefault();

            ViewBag.user = user;

            return View(user);
        }


        [HttpPost]//保存信息
        //wst_users user
        public ActionResult UserInfo(FormCollection collection, int id = 1)
        {

            try
            {
                var message = dbContext.wst_users.Single(a => a.userId == id);

                UpdateModel(message);

                dbContext.SaveChanges();

                //修改成功返回到页面
                return RedirectToAction("UserInfo");

            }
            catch
            {

                return View();

            }

        }
        #endregion

        #region 个人头像编辑设置
        [HttpGet]
        public ActionResult UserPortrait()
        {

            return View();
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult UploadImg(wst_users user)
        {
            //wst_users user = Session["User"] as wst_users;

            ////string name = user.userImage;

            //if (Request.Files.Count > 0)
            //{

            //    //用于获取上传的文件
            //    HttpPostedFileBase file = Request.Files["file1"];

            //    var savePath = Server.MapPath("~/UserImage/" + user.userImage);

            //    file.SaveAs(savePath);

            //    UpdateModel(user);

            //    int result = dbContext.SaveChanges();

            //    if (result > 0)
            //    {
            //        return RedirectToAction("Destination");
            //    }

            //}


            HttpFileCollectionBase files = Request.Files;

            HttpPostedFileBase file = Request.Files["file1"];

            string extName = Path.GetExtension(file.FileName).ToLower();

            string path = Server.MapPath("~/UserImage/");

            string fileNewName = System.Guid.NewGuid().ToString();

            file.SaveAs(path + fileNewName + extName);

            return Content(fileNewName + extName);



            //HttpFileCollectionBase files = Request.Files;

            //HttpPostedFileBase file = Request.Files["file1"];

            //string extName = Path.GetExtension(file.FileName).ToLower();

            //string path = Server.MapPath("~/UserImage/");

            ////生成新文件的名称，guid保证某一时刻内唯一的（保证了文件不会被覆盖）
            //string fileNewName = System.Guid.NewGuid().ToString();

            //file.SaveAs(path + fileNewName + extName);

            //user.userImage = fileNewName+extName;

            //return View();
        }
        #endregion

        #region 更多个人信息
        public ActionResult UserInfoMore()
        {

            return View();
        }
        #endregion

        #region 账户安全
        public ActionResult UserAnQuan()
        {

            return View();
        }
        #endregion

        #region 修改手机验证
        public ActionResult UserUpPhone()
        {

            return View();
        }
        #endregion

        #region 收货地址

        wst_user_address userAddress = new wst_user_address();

        public ActionResult Destination(int addressId = 1)
        {
            //获取显示地址数据源
            var address = dbContext.wst_user_address.Where(a => addressId == 0 ? true : a.userId == addressId).Take(5).ToList();

            //将数据保存在ViewBag
            ViewBag.address = address;

            return View();
        }


        /// <summary>
        /// 添加地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Add()
        {
            try
            {

                wst_user_address user = new wst_user_address();
                user.userName = Request["userName"];
                user.userAddress = Request["userAddress"];
                user.userPhone = Request["userPhone"];

                user.createTime = DateTime.Now;
                user.isDefault = 0;
                user.dataFlag = 1;
                user.userId = 1;

                ViewData.Model = user;
                dbContext.wst_user_address.Add(user);
                dbContext.SaveChanges();
                return RedirectToAction("Destination", "User");


            }
            catch (Exception ex)
            {

                return Content("添加失败," + ex.Message);
            }
        }











        /// <summary>
        /// 修改地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult updateDistrict(string id)
        {
            this.TempData["id"] = id;
            //编辑时，显示字段

            wst_user_address wua = dbContext.wst_user_address.Where(p => p.userId.ToString() == id).FirstOrDefault();
            return Json(wua, JsonRequestBehavior.AllowGet);

        }



        /// <summary>
        /// 保存修改配置
        /// </summary>
        /// <returns></returns>
        public JsonResult saveUpdateDistrict(FormCollection form)
        {
            wst_user_address entity;
            string uID = this.TempData["id"] as string;
            string userName = form["userNames"];
            string userPhone = form["userPhones"];
            string userAddress = form["userAddresss"];

            entity = dbContext.wst_user_address.Where(p => p.userId.ToString() == uID).FirstOrDefault();

            if (entity != null)
            {
                var entity1 = dbContext.wst_user_address.Where(p => p.userName == userName).FirstOrDefault();
                if (entity1 == null || entity.userName == userName)
                {
                    entity.userName = userName;
                    entity.userPhone = userPhone;
                    entity.userAddress = userAddress;

                    dbContext.SaveChanges();
                    return Json(true);
                }
                else
                {
                    return Json(false);
                }
            }
            else
            {
                return Json(false);
            }
        }







        ////修改地址
        //public ActionResult Edit(int id)
        //{
        //    userAddress = dbContext.Set<wst_user_address>().Where(u => u.addressId == id).FirstOrDefault();

        //    return View(userAddress);
        //}


        //[HttpPost]
        //public ActionResult EditAddress(int Address)
        //{
        //    string Str = "NO";
        //    var userAddress = dbContext.wst_user_address.Find(Address);
        //    if (userAddress != null)
        //    {
        //        ViewBag.userAddress = userAddress;
        //        Str = "YES";
        //    }

        //    //获取模型的值
        //    if (!ModelState.IsValid)
        //    {
        //        return Content("error");
        //    }

        //    //将对象添加到EF容器当中
        //    dbContext.wst_user_address.Attach(userAddress);

        //    dbContext.Entry(userAddress).State = EntityState.Modified;

        //    //将上下文所做的更改保存在数据库当中
        //    dbContext.SaveChanges();

        //    return Content(Str);
        //}








        //删除地址
        [HttpPost]
        public ActionResult Delete(int id)
        {
            userAddress.addressId = id;

            dbContext.wst_user_address.Attach(userAddress);

            dbContext.Entry(userAddress).State = EntityState.Deleted;

            dbContext.SaveChanges();

            return Content("ok");

        }
        #endregion

        #region 评价晒单
        public ActionResult UserComment()
        {

            return View();
        }
        #endregion

        #region 订单商品评价
        public ActionResult GoodsComment()
        {


            return View();
        }
        #endregion       


    }
}
